package com.pureland.security.context;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pureland.common.exception.CheckedException;
import com.pureland.security.entity.AuthInfo;
import com.pureland.security.exceptions.ServerErrorException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;


/**
 * @projectName: pureland_cloud
 * @className: com.pureland.security.context.SecurityContext
 * @description: 认证上下文
 * @author: tong.li
 * @createTime: 2020/11/17 18:14
 * @version: v1.0
 * @copyright: 版权所有 李彤 © 2020
 */
public class SecurityContext {


    private static Logger logger = LoggerFactory.getLogger(SecurityContext.class);

    public static final String ANONYMOUS_USER = "anonymousUser";

    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static OAuth2Authentication getAuthentication() {
        return (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取用户详细信息(只适用于 authority 模块)
     *
     * @return 结果
     */
    public static AuthInfo getAuthInfo() {
        OAuth2Authentication authentication = getAuthentication();
        if (authentication == null) {
            throw CheckedException.forbidden("认证信息不存在");
        }
        Authentication userAuthentication = authentication.getUserAuthentication();
        if (userAuthentication.getPrincipal() instanceof AuthInfo) {
            return (AuthInfo) userAuthentication.getPrincipal();
        }
        String json = null;
        try {
            json = objectMapper.writeValueAsString(userAuthentication.getDetails());
            if (StringUtils.isNoneBlank(json)) {
                return objectMapper.readValue(json,AuthInfo.class);
            }
        } catch (JsonProcessingException e) {
            logger.error("getAuthInfo JsonProcessingException error",e);
        }
        throw new ServerErrorException("authinfo error");
    }




    public boolean isAuth() {
        final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            return false;
        }
        if (authentication.getPrincipal() == null) {
            return false;
        }
        return !authentication.getPrincipal().equals(ANONYMOUS_USER);
    }


    /**
     * 是否为匿名用户
     *
     * @return 是（true）|不是（false）
     */
    public static boolean anonymous() {
        final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            return true;
        }
        return authentication.getPrincipal().equals(ANONYMOUS_USER);
    }




}
